package com.pinyoumei.app.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.pinyoumei.app.R;
import com.pinyoumei.app.bean.BaseBean;
import com.pinyoumei.app.bean.CodeBean;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.EventBusUtils;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.utils.ToastUtils;
import com.pinyoumei.app.utils.event.ReshEvent;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2020-08-18.
 * --------- 日期 ------- 维护人 ------------ 变更内容 --------
 * 2020-08-18        Administrator             新增Person类
 * 2020-08-18        Administrator             增加sex属性
 * 绑定手机号
 */
public class BindPhoneActivity extends BaseActivity implements View.OnClickListener {

    private EditText etPhone;
    private EditText etCode;
    private TextView tvSendCode;
    private Button btNext;
    private BindPhoneActivity.TimeCount timeCount;//计时器类


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind_phone);

        InitWidget();



    }

    private void InitWidget() {


        timeCount = new TimeCount(60 * 1000, 1000);
        RelativeLayout relativeFinish = findViewById(R.id.relative_finish);
        relativeFinish.setOnClickListener(this);
        etPhone = findViewById(R.id.et_phone);
        etCode = findViewById(R.id.et_code);
        tvSendCode = findViewById(R.id.tv_send_code);
        tvSendCode.setOnClickListener(this);
        btNext = findViewById(R.id.bt_next);
        btNext.setOnClickListener(this);



    }




    //获取短信验证码的方法
    private void SendCode(String phone,int type) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_phone", phone);
        map.put("type", type);

        OkGo.<String>post(Constants.SendMSG)
                .params("user_phone", phone)
                .params("type", type)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        CodeBean codeBean = gson.fromJson(response.body(), CodeBean.class);

                        if (codeBean.getCode() >= 0) {

                            if (timeCount == null) {
                                timeCount = new BindPhoneActivity.TimeCount(60 * 1000, 1000);//5s的一个定时器 间隔是1s
                                timeCount.start();
                            }

                            Toast.makeText(BindPhoneActivity.this, codeBean.getMsg(), Toast.LENGTH_SHORT).show();

                        } else {
                            Toast.makeText(BindPhoneActivity.this, codeBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });


    }



    private void bind_submit(String verify_code,String user_phone) {
            Map<String,Object> map = new HashMap<>();
            map.put("user_id", SPUtils.getAppUserId(this));
            map.put("verify_code", verify_code);
            map.put("user_phone", user_phone);

            OkGo.<String>post( Constants.UPDATE_PHONE_BIND_SUBMIT)
                    .params("user_id",SPUtils.getAppUserId(this))
                    .params("verify_code", verify_code)
                    .params("user_phone", user_phone)
                    .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                    .execute(new StringCallback() {


                        @Override
                        public void onStart(Request<String, ? extends Request> request) {
                            super.onStart(request);
                            loadingDailog.show();
                        }

                        @Override
                        public void onCacheSuccess(Response<String> response) {
                            super.onCacheSuccess(response);
                            setData(response);
                        }

                        @Override
                        public void onSuccess(Response<String> response) {
                            setData(response);

                        }

                        private void setData(Response<String> response) {
                            loadingDailog.dismiss();
                            BaseBean baseBean = gson.fromJson(response.body(), BaseBean.class);
                            if (baseBean.getCode() >= 0 ){
                                EventBusUtils.post(new ReshEvent("1"));
                                appManager.killActivity(ChangePhoneActivity.class);
                                finish();
                            }else{
                                ToastUtils.showShort(baseBean.getMsg());

                            }
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            loadingDailog.dismiss();
                        }
                    });

        }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        	case R.id.relative_finish:
        		finish();
        		break;

        		case R.id.tv_send_code:
                    if (!TextUtils.isEmpty(etPhone.getText().toString().trim())){
                        SendCode( etPhone.getText().toString(), 3);//短信验证码类型： 1 注册 2忘记密码 3实名认证更换手机号
                    }else {
                        Toast.makeText(mContext, "请输入新的手机号码", Toast.LENGTH_SHORT).show();
                    }
        		break;

        		case R.id.bt_next:
        		//完成绑定
                    String Phone = etPhone.getText().toString().trim();
                    String code = etCode.getText().toString().trim();
                    if (TextUtils.isEmpty(Phone)){
                        Toast.makeText(mContext, "请输入新的手机号码", Toast.LENGTH_SHORT).show();
                    }else if (TextUtils.isEmpty(code)){
                        Toast.makeText(mContext, "请输入验证码", Toast.LENGTH_SHORT).show();
                    }else {
                        bind_submit(code,Phone);
                    }

        		break;

        	default:
        		break;
        }
    }

    //计时器类
        class TimeCount extends CountDownTimer {
        //构造方法
        public TimeCount(long millisInFuture, long countDownInterval) {//第一个参数是计时器的总时间是60s 第二个参数是间隔是1s
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            tvSendCode.setText("重新获取(" + millisUntilFinished / 1000 + "s)");
            tvSendCode.setTextColor(Color.parseColor("#438FF5"));
            tvSendCode.setClickable(false);
        }

        @Override
        public void onFinish() {
            tvSendCode.setText("获取验证码");
            tvSendCode.setTextColor(Color.parseColor("#438FF5"));
            tvSendCode.setClickable(true);
        }
    }
}
